#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* string 长度是多大? */
int my_itoa_any_binary(int value, char *string, int base)
{
	int i = 0,j = 0;
	int tmp = 0;
	char a[128] = {'\0'};
	
	while ((value / base) && i < 127) {
		tmp = value % base;
		a[i++] = tmp + '0';
		value = value / base;
	}
	a[i] = value + '0';

	while (i && j < 127) {
		string[j++] = a[i--];
	}

	if (i == 0) {
		string[j++] = a[i];
	}
	string[j] = '\0';

	return 0;
}

int my_itoa(int value, char *string)
{
	int i = 0,j = 0;
	int tmp = 0;
	char a[128] = {'\0'};
	while ((value /10) && i < 127) {
		tmp = value % 10;
		a[i++] = tmp + '0';
		value = value / 10;
	}
	a[i] = value + '0';

	while (i && j < 127) {
		string[j++] = a[i--];
	}

	if (i == 0) {
		string[j++] = a[i];
	}
	string[j] = '\0';

	return 0;
}

int my_atoi(char *str)
{
	int i = 0;
	if (NULL == str)
		return -1;

	while (*str) {
		if ('0' <= *str && *str <= '9') {
			i = (i * 10) + *str++ - '0';
			printf("i = %d\n", i);
		} else {
			str++;
		}
	}

	return i;
}

static void my_atoi_test(void)
{
	int i = 0;

	/* 仅处理数字 */
	i = my_atoi("1234cd/ls/clear/5678");
	printf("my_atoi:%d\n", i);

	/* 遇到非数字即停止 实际实现是strtol */
	i = atoi("1234cd/ls/clear/5678");
	printf("atoi:%d\n", i);

	/* 遇到非数字即停止 */
	i = strtol("1234cd/ls/clear/5678", NULL, 10);
	printf("strtol:%d\n", i);
}

void print_specil_display(void)
{
	printf("%#o %d\n", 010, 010);/* #自动加0x(16进制) 0 */
}

void my_itoa_test(void)
{
	char *p = "12345678";
	int i = 0;
	i = atoi(p);
	char str[128] = {0};
	
	my_itoa(12345678, str);
	printf("%s\n",str);

	snprintf(str, sizeof(str), "%s", "string"); /* 格式化处理  */
	printf("str: %s\n", str);

	snprintf(str, sizeof(str), "%o", 10);/* 整型按照8进制转换为字符串 */
	printf("str: %s\n", str);

	my_itoa_any_binary(11, str, 8); /* 整型按照8进制转化为字符串 */
	printf("str: %s\n", str);

	my_itoa_any_binary(11, str, 2);/* 整型按照2进制转化为字符串 */
	printf("str: %s\n", str);
}

int main(void)
{
	
	return 0;
}

